/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    ListNode *deleteDuplicates(ListNode *head)
    {
        auto cur = head;
        auto pseudoHead = new ListNode();
        auto last = pseudoHead;
        last->next = head;
        bool curDuplicate = false;
        while (cur != nullptr)
        {
            if (cur->next != nullptr && cur->val == cur->next->val)
            {
                cur->next = cur->next->next;
                curDuplicate = true;
            }
            else if (curDuplicate)
            {
                last->next = cur->next;
                cur = cur->next;
                curDuplicate = false;
            }
            else
            {
                last = last->next;
                cur = cur->next;
            }
        }
        return pseudoHead->next;
    }
};